package com.sgb.capital.view.ui.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.scwang.smart.refresh.layout.listener.ScrollBoundaryDecider
import com.sgb.capital.R
import com.sgb.capital.callback.Constants
import com.sgb.capital.callback.ZMessageEvent
import com.sgb.capital.databinding.CommoditylistFragmentBinding
import com.sgb.capital.model.Bean
import com.sgb.capital.model.CommodityBean
import com.sgb.capital.utils.SPreferenceUtil
import com.sgb.capital.utils.Utils
import com.sgb.capital.view.ui.adapter.CommodityListAdapter
import com.sgb.capital.view.widget.BaseRecyclerViewAdapterHelper.BaseQuickAdapter
import com.sgb.capital.viewmodel.CommodityModel
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe


/**
 * 作者:张磊
 * 日期:2021/11/19 0019
 * 说明:商品的询价或报价  tip: 可在资金中心模块独立运行不建议复用
 */
class CommodityFragment : AppLazyFragment() {
    private lateinit var mBinding: CommoditylistFragmentBinding
    private lateinit var mModel: CommodityModel
    private var isLoadMore = false //是否加载更多
    private var isEnableLoadMore = false //是否能加载更多
    private lateinit var mAdapter: CommodityListAdapter
    private var mPos = 0 // 0: 收到 1:发起
    private var mType: String? = null // 区别询价或报价
    private var mPage = 1 // 分页


    companion object {
        fun newInstance(type: String?): CommodityFragment {
            val fragment = CommodityFragment()
            val bundle = Bundle()
            bundle.putString("type", type)
            fragment.arguments = bundle
            return fragment
        }
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.commoditylist_fragment, container, false)
        return mBinding.root
    }

    override fun initView() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        val arguments = arguments
        mType = arguments!!.getString("type", "报价")
        mModel = ViewModelProvider(this)[CommodityModel::class.java]
        mBinding.rv.layoutManager = LinearLayoutManager(Utils.getContext())
        mAdapter = CommodityListAdapter(null)
        mAdapter.mType = mType
        val empty: View = LayoutInflater.from(activity).inflate(R.layout.capital_layout_empty_view, mBinding.rv, false)
        mAdapter.setEmptyView(empty)
        mBinding.rv.adapter = mAdapter
    }

    override fun onLazyLoad() {
        mPage = 1
        mAdapter.mPos = mPos
        if (mPos == 0) {
            if (mType!!.contains("报价")) {
                mModel.receivedQuotedList(activity, 10, mPage)
            } else {
                val saveIntData = SPreferenceUtil.getInstance().getSaveIntData(SPreferenceUtil.COM_TYPE, 0)
                if (saveIntData==0){
                    mModel.enquiryList(activity, 10, mPage)
                }else {
                    mModel.receivedEnquiryList(activity, 10, mPage)
                }
            }
        } else {
            if (mType!!.contains("报价")) {
                mModel.publishQuotedEnquiryList(activity, 10, mPage)
            } else {
                mModel.enquiryList(activity, 10, mPage)
            }
        }
    }

    override fun initListener() {
        mAdapter.setOnItemClickListener { adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int ->
            val data = mAdapter.data[position]
            Utils.sendMsg(Constants.EVENT_CLICK, data)
        }
        mBinding.srl.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onLoadMore(refreshLayout: RefreshLayout) {
                isLoadMore = true
                mPage++
                if (mType!!.contains("报价")) {
                    if (mPos == 0) {
                        mModel.receivedQuotedList(activity, 10, mPage)
                    } else {
                        mModel.publishQuotedEnquiryList(activity, 10, mPage)
                    }
                } else {
                    if (mPos == 0) {
                        val saveIntData = SPreferenceUtil.getInstance().getSaveIntData(SPreferenceUtil.COM_TYPE, 0)
                        if (saveIntData==0){
                            mModel.enquiryList(activity, 10, mPage)
                        }else {
                            mModel.receivedEnquiryList(activity, 10, mPage)
                        }
                    } else {
                        mModel.enquiryList(activity, 10, mPage)
                    }
                }
                mBinding.srl.finishLoadMore(500)
            }

            override fun onRefresh(refreshLayout: RefreshLayout) {
                isLoadMore = false
                mPage = 1
                if (mType!!.contains("报价")) {
                    if (mPos == 0) {
                        mModel.receivedQuotedList(activity, 10, mPage)
                    } else {
                        mModel.publishQuotedEnquiryList(activity, 10, mPage)
                    }
                } else {
                    if (mPos == 0) {
                        val saveIntData = SPreferenceUtil.getInstance().getSaveIntData(SPreferenceUtil.COM_TYPE, 0)
                        if (saveIntData==0){
                            mModel.enquiryList(activity, 10, mPage)
                        }else {
                            mModel.receivedEnquiryList(activity, 10, mPage)
                        }
                    } else {
                        mModel.enquiryList(activity, 10, mPage)
                    }
                }
                mBinding.srl.finishRefresh(500)
            }
        })
        mBinding.srl.setScrollBoundaryDecider(object : ScrollBoundaryDecider {
            override fun canRefresh(content: View): Boolean {
                return mBinding.rv.computeVerticalScrollOffset() === 0
            }

            override fun canLoadMore(content: View): Boolean {
                val scrollRange: Int = mBinding.rv.computeVerticalScrollRange()
                val scrollOffset: Int = mBinding.rv.computeVerticalScrollOffset()
                val scrollExtent: Int = mBinding.rv.computeVerticalScrollExtent()
                val height: Int = mBinding.rv.height
                return if (height > scrollRange) {
                    false
                } else isEnableLoadMore && scrollRange <= scrollOffset + scrollExtent
            }
        })
    }

    override fun initObserve() {
        mModel.mCommodityBean.observe(this, { data: CommodityBean? ->
            if (data == null) return@observe
            isEnableLoadMore = data.list.size >= 10
            if (isLoadMore) {
                mAdapter.addData(data.list)
            } else {
                mAdapter.setNewInstance(data.list)
            }
            Utils.sendMsg(Constants.EVENT_REFRESH_COUNT, data.totalRow)
        })
    }

    override fun onDestroy() {
        EventBus.getDefault().unregister(this)
        super.onDestroy()
    }

    @Subscribe
    fun getCode(event: ZMessageEvent) {
        when (event.code) {
            Constants.EVENT_REFRESH_COMMODITY -> {
                val bean = event.data as Bean
                mPos = bean.posFirst
                if (mType!!.contains("报价")) {
                    if (bean.posSecond == 2) {
                        onLazyLoad()
                    }
                } else {
                    if (bean.posSecond == 0) {
                        onLazyLoad()
                    }
                }
            }
        }
    }
}